package com.meixiang.view;

import android.annotation.TargetApi;
import android.content.Context;
import android.os.Build;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutCompat;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.meixiang.R;
import com.meixiang.inteface.IcalendarOnclick;
import com.meixiang.recyclerview.OnItemClick;
import com.meixiang.recyclerview.RecyclerAdapter;
import com.meixiang.util.DensityUtil;
import com.meixiang.view.Calendar.DataUtils;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * 日历
 * xiejingwen
 */
public class CalendarView extends LinearLayoutCompat implements View.OnClickListener {
    private ImageView ivLeft; //上一个月
    private TextView tv_date; //当前日期
    private ImageView ivRight; //下一个月
    private Context mContext;
    //private ViewPager viewPager;
    private RecyclerView recycler; //日历内容
    private List<CalendarEntity> Months; //日历数据

    private List<CalendarEntity> unCheckDate;//不可选时间

    private int year; //年
    private int month; //月份
    private int week; //月份1号是星期几
    private int days; //月份天数


    private int nowYear; //用于记录当前时间  小于当前时间则不可点击
    private int nowMonth;

    private  CalendarAdapter calendarAdapter;

    private Calendar calendar;

    private IcalendarOnclick onclick;
    private String nowTime;
    public CalendarView(Context context) {
        this(context, null);
    }

    public CalendarView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public CalendarView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        setOrientation(VERTICAL);
        mContext = context;
        initView();
    }

    /**
     * 设置不可点击的日期
     * @param holidayList
     */
    public void setUnCheckDate(List<String> holidayList){

        unCheckDate=new ArrayList<>();
        for (int i=0;i<holidayList.size();i++){
            String[] holiday=holidayList.get(i).split("-");
            CalendarEntity calendar=new CalendarEntity();
            calendar.setYear(Integer.parseInt(holiday[0]));
            calendar.setMonth(Integer.parseInt(holiday[1]));
            calendar.setDay(Integer.parseInt(holiday[2]));
            unCheckDate.add(calendar);
        }
        setDate(year, month);
    }

    /**
     * 根据传入的时间显示日历
     * @param year
     * @param month
     */
    private void setDate(int year,int month){
        tv_date.setText(year + " 年 " + month + " 月");
        initData(year,month);
        calendarAdapter.AddData(Months);
    }

    /**
     * 外部调用，根据传入的时间显示日历
     * @param nowYear
     * @param nowMonth
     */
    public void setNowDate(int nowYear,int nowMonth){
        this.nowYear=nowYear;
        this.nowMonth=nowMonth;
        this.year=nowYear;
        this.month=nowMonth;
        setDate(year, month);
    }


    private void initView() {
        View view = LayoutInflater.from(mContext).inflate(R.layout.view_calendar_head, null);
        ivLeft = (ImageView) view.findViewById(R.id.iv_left);
        tv_date = (TextView) view.findViewById(R.id.tv_date);
        ivRight = (ImageView) view.findViewById(R.id.iv_right);
        ivLeft.setOnClickListener(this);
        ivRight.setOnClickListener(this);
        calendar=Calendar.getInstance();
        year=calendar.get(calendar.YEAR);
        month=calendar.get(calendar.MONTH)+1;
        nowYear=calendar.get(calendar.YEAR);
        nowMonth=calendar.get(calendar.MONTH)+1;
        addView(view);
        recycler = new RecyclerView(mContext);
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
        recycler.setLayoutParams(layoutParams);
        recycler.setLayoutManager(new GridLayoutManager(mContext, 7));
        recycler.setBackgroundColor(ContextCompat.getColor(mContext, R.color.white));
        recycler.setPadding(0, 0, 0, DensityUtil.dip2px(mContext, 18));
        calendarAdapter=new CalendarAdapter();
        setDate(year, month);

        recycler.setAdapter(calendarAdapter);
        calendarAdapter.setOnItemClickListener(new OnItemClick() {
            @Override
            public void onItemClick(View view, int position) {
                CalendarEntity entity=calendarAdapter.Months.get(position);
                if (!entity.isChecked()){
                    return;
                }
                if (entity.getDay()!=-1){
                    if (onclick!=null){
                        onclick.getOnclickDate(calendarAdapter.Months.get(position).getTime());
                    }
                }
            }
        });

        addView(recycler);
    }
    public void setICalendarOnclickListener(IcalendarOnclick onclick){
        this.onclick=onclick;
    }
    /**
     * 初始化数据
     */
    public void initData(int year,int month){
        Months=new ArrayList<>();
        week= DataUtils.getFirstDayWeek(year,month-1);
        days=DataUtils.getMonthDays(year,month-1);
        //设置空格
        for (int i=1;i<week;i++){
            CalendarEntity entity=new CalendarEntity();
            entity.setDay(-1);
            Months.add(entity);
        }
        for (int i=1;i<=days;i++){
            CalendarEntity entity=new CalendarEntity();
            entity.setYear(year);
            entity.setMonth(month);
            entity.setDay(i);
            if (isUnCheckDate(entity)){
                entity.setChecked(false);
            }else{
                entity.setChecked(true);
            }
            String time=year+"-";//拼接年
            time=month<10?time+"0"+month+"-":time+month+"-";//拼接月，小于10加0
            time=i<10?time+"0"+i:time+i;//拼接日
            entity.setTime(time);
            Months.add(entity);
        }

    }

    /**
     *  判断哪些日期是不可选的
     * @param entity
     * @return
     */
    private boolean isUnCheckDate(CalendarEntity entity){
        //小于当天的不可点击
        if ( calendar.get(Calendar.YEAR)==entity.getYear()&&calendar.get(Calendar.MONTH)+1==entity.getMonth()&&calendar.get(Calendar.DAY_OF_MONTH)>entity.getDay()){
            return true;
        }

        if (unCheckDate==null||unCheckDate.size()==0){
            return false;
        }
        for (int i=0;i<unCheckDate.size();i++){
            if (entity.getYear()==unCheckDate.get(i).getYear()&&entity.getMonth()==unCheckDate.get(i).getMonth()&&entity.getDay()==unCheckDate.get(i).getDay()){
                return true;
            }
        }
        return false;
    }
    /**
     * 设置显示日期的颜色
     * @param ResId
     */
    public void setDateColor(int ResId) {
        tv_date.setTextColor(ContextCompat.getColor(mContext, ResId));
    }

    @Override
    public void onClick(View v) {
        if (v.equals(ivLeft)) {
            if (nowYear==year&&nowMonth<month||nowYear<year){
                if (month==1){
                    year--;
                    month=12;
                }else{
                    month--;
                }
                setDate(year,month);
            }
        } else if (v.equals(ivRight)) {
            if (month==12){
                year++;
                month=1;
            }else{
                month++;
            }
            setDate(year,month);
        }
        if (nowYear==year&&nowMonth==month){
            ivLeft.setImageDrawable(ContextCompat.getDrawable(mContext,R.mipmap.month_3));
        }else{
            ivLeft.setImageDrawable(ContextCompat.getDrawable(mContext,R.mipmap.back));
        }
    }


    class CalendarAdapter extends RecyclerAdapter<CalendarAdapter.ViewHolder> {
        public List<CalendarEntity> Months=new ArrayList<>();

        public void AddData(List<CalendarEntity> Months){
            this.Months.clear();
            this.Months.addAll(Months);
            notifyDataSetChanged();
        }
        @Override
        public CalendarAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(mContext).inflate(R.layout.calendar_item, parent, false);
            return new ViewHolder(view);
        }

        @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
        @Override
        public void onBindViewHolder(CalendarAdapter.ViewHolder holder, final int position) {
            if (Months.get(position).getDay()==-1){
                holder.tvNumber.setText("");
                holder.tvNumber.setBackgroundColor(ContextCompat.getColor(mContext,R.color.white));
            }else if (calendar.get(Calendar.YEAR)==Months.get(position).getYear()&&calendar.get(Calendar.MONTH)+1==Months.get(position).getMonth()&&calendar.get(Calendar.DAY_OF_MONTH)==Months.get(position).getDay()){
                holder.tvNumber.setText("今天");
                holder.tvNumber.setBackgroundResource(R.drawable.calendar_unchecked);
            }else{
                holder.tvNumber.setText(Months.get(position).getDay()+"");
                holder.tvNumber.setBackgroundResource(R.drawable.calendar_unchecked);
            }
            if (Months.get(position).getDay()!=-1){
                if (Months.get(position).isChecked()){
                    holder.tvNumber.setBackgroundResource(R.drawable.calendar_checked);
                    holder.tvNumber.setTextColor(ContextCompat.getColor(mContext,R.color.white));
                }else{
                    holder.tvNumber.setBackgroundResource(R.drawable.calendar_unchecked);
                    holder.tvNumber.setTextColor(ContextCompat.getColor(mContext,R.color.black_9));
                }
            }
        }

        @Override
        public int getItemCount() {
            return Months.size();
        }

       class ViewHolder extends RecyclerView.ViewHolder{
            @Bind(R.id.tv_number)
            TextView tvNumber;
            ViewHolder(View view) {
                super(view);
                ButterKnife.bind(this, view);
            }
        }

    }

}
